package triangle.reader;

import org.junit.Assert;
import org.junit.rules.TemporaryFolder;

import java.io.File;
import java.util.Iterator;
import java.util.LinkedList;

/**
 * This file is part of Rodney Ryan's submission of
 * his solution to the "Triangle Puzzle".
 *
 * rodney@rodneyryan.com
 */
public class ReadingStrategyTester {

    private ReadingStrategy readingStrategy;
    private TestFileCreator testFileCreator;

    public ReadingStrategyTester(ReadingStrategy readingStrategy, TemporaryFolder testFolder, String fileNamePrefix) {
        super();
        this.readingStrategy = readingStrategy;
        testFileCreator = new TestFileCreator(testFolder, fileNamePrefix);
    }

    private String writeAndReadFile(String fileContents) throws Exception {
        String testFilePath = testFileCreator.createTestFile(fileContents);

        readingStrategy.open(new File(testFilePath));

        StringBuilder stringBuilder = new StringBuilder();
        String line = readingStrategy.readPreviousLine();
        while (line != null) {
            stringBuilder.append(line);
            line = readingStrategy.readPreviousLine();
            if (line != null) {
                stringBuilder.append(",");
            }
        }

        readingStrategy.close();
        return stringBuilder.toString();
    }

    private String createExpected(String fileText) {
        LinkedList<String> linkedList = new LinkedList<String>();
        String[] lines = fileText.split("\n");
        for (String line : lines) {
            line = line.trim();
            if (line.length() != 0) {
                linkedList.addFirst(line);
            }
        }

        StringBuilder stringBuilder = new StringBuilder();
        Iterator<String> iterator = linkedList.iterator();
        while (iterator.hasNext()) {
            stringBuilder.append(iterator.next());
            if (iterator.hasNext()) {
                stringBuilder.append(",");
            }
        }
        return stringBuilder.toString();
    }

    public void test(String fileText) throws Exception {
        String actual = writeAndReadFile(fileText);
        String expected = createExpected(fileText);

        Assert.assertEquals(expected, actual);
    }
}

